{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# pytorch 小练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实现softmax函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "def softmax(x):\n",
    "    \"\"\"\n",
    "    实现 softmax 函数，只对最后一维归一化。\n",
    "    \"\"\"\n",
    "    x_exp = torch.exp(x)\n",
    "    partition = x_exp.sum(dim=-1, keepdim=True)\n",
    "    return x_exp / partition\n",
    "\n",
    "# 测试 softmax\n",
    "test_data = torch.tensor(np.random.normal(size=[10, 5]), dtype=torch.float32)\n",
    "print(torch.allclose(softmax(test_data), torch.nn.functional.softmax(test_data, dim=-1), atol=1e-4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实现sigmoid函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "def sigmoid(x):\n",
    "    \"\"\"\n",
    "    实现 sigmoid 函数。\n",
    "    \"\"\"\n",
    "    return 1 / (1 + torch.exp(-x))\n",
    "\n",
    "# 测试 sigmoid\n",
    "test_data = torch.tensor(np.random.normal(size=[10, 5]), dtype=torch.float32)\n",
    "print(torch.allclose(sigmoid(test_data), torch.sigmoid(test_data), atol=1e-4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实现 softmax 交叉熵loss函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "def softmax_ce(logits, labels):\n",
    "    \"\"\"\n",
    "    实现 softmax 交叉熵 loss 函数。\n",
    "    logits: 预测的未归一化概率值。\n",
    "    labels: 独热编码的真实标签。\n",
    "    \"\"\"\n",
    "    probs = softmax(logits)\n",
    "    loss = -torch.sum(labels * torch.log(probs + 1e-9), dim=-1)\n",
    "    return loss.mean()\n",
    "\n",
    "# 测试 softmax 交叉熵\n",
    "test_data = torch.tensor(np.random.normal(size=[10, 5]), dtype=torch.float32)\n",
    "labels = torch.zeros_like(test_data)\n",
    "labels[torch.arange(10), torch.randint(0, 5, (10,))] = 1\n",
    "print(torch.allclose(softmax_ce(test_data, labels), torch.nn.functional.cross_entropy(test_data, labels, reduction='mean'), atol=1e-4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实现 sigmoid 交叉熵loss函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "def sigmoid_ce(logits, labels):\n",
    "    \"\"\"\n",
    "    实现 sigmoid 交叉熵 loss 函数。\n",
    "    logits: 预测的未归一化概率值。\n",
    "    labels: 二分类标签 (0 或 1)。\n",
    "    \"\"\"\n",
    "    loss = - (labels * torch.log(sigmoid(logits) + 1e-9) + (1 - labels) * torch.log(1 - sigmoid(logits) + 1e-9))\n",
    "    return loss.mean()\n",
    "\n",
    "# 测试 sigmoid 交叉熵\n",
    "test_data = torch.tensor(np.random.normal(size=[10]), dtype=torch.float32)\n",
    "labels = torch.tensor(np.random.randint(0, 2, 10), dtype=torch.float32)\n",
    "print(torch.allclose(sigmoid_ce(test_data, labels), torch.nn.functional.binary_cross_entropy_with_logits(test_data, labels, reduction='mean'), atol=1e-4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.21"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
